<?php

namespace App\Admin\Controllers;

use App\Models\Category;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CategoryController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('分类管理');
            $content->description('拖动左边分类栏后点击保存可改变排序');

            $content->row(function (Row $row) {
                $row->column(6, $this->treeView()->render());

                $row->column(6, function (Column $column) {
                    $form = new \Encore\Admin\Widgets\Form();
                    $form->action(admin_base_path('/category'));

                    $form->select('p_id', trans('admin.parent_id'))->options(Category::selectOptions());
                    $form->text('name', trans('admin.title'))->rules('required');

                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Category::class, function (Grid $grid) {

            $grid->id('ID')->sortable();

            $grid->created_at();
            $grid->updated_at();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Category::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->select('p_id', trans('admin.parent_id'))->options(Category::selectOptions());
            $form->text('name', trans('admin.title'))->rules('required');

//            $form->display('created_at', 'Created At');
//            $form->display('updated_at', 'Updated At');

        });
    }

    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
        return Category::tree(function (Tree $tree) {
            $tree->disableCreate();
            $tree->branch(function ($branch) {
//                $branch->disableDelete();
                $payload = "<i class='fa'></i>&nbsp;<strong>{$branch['name']}</strong>";

                return $payload;
            });
        });
    }

    public function destroy($id)
    {
        $ids = explode(',', $id);

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if (empty($id))
                    continue;
                if (!Category::select('id', 'p_id')->find($id)->delete()) {
                    return response()->json([
                        'status' => false,
                        'message' => '删除失败,该分类下包含有子菜单或含有产品且无上级分类.',
                    ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::info('Database Error :' . $e->getMessage());
        }

        return response()->json([
            'status'  => true,
            'message' => '删除成功'
        ]);
    }

    public function store(Request $request)
    {
        $pid = $request->input('p_id');
        $name = $request->input('name');

        if ($pid == 0)
        {
            $newCategory = new Category();
            $newCategory->name = $name;
            $newCategory->p_id = 0;
            $newCategory->level = 1;
            $newCategory->save();

            admin_toastr('添加成功!', 'success');
            return redirect(admin_base_path('category'));
        }

        $parent = Category::select('id', 'name', 'level')->find($pid);

        $newCategory = new Category();
        $newCategory->name = $name;
        $newCategory->p_id = $pid;
        $newCategory->level = $parent->level + 1;
        $newCategory->save();

        admin_toastr('添加成功', 'success');
        return redirect(admin_base_path('category'));
    }

    public function lists(Request $request)
    {
        $q = $request->input('q');
        $category = Category::select('id', 'p_id', 'level')->find($q);

        if (!$category)
        {
            $files = Category::where('p_id', $q)
                ->paginate(null, ['id', 'name as text']);

            return $files;
        }

        if ($category->level == 1)
        {
            $categoryObj = Category::whereIn('p_id', $category->children()->pluck('id'));
        } else {
            $categoryObj = Category::where('p_id', $category->id);
        }

        $category = $categoryObj->with(['children' => function($q) {
                $q->select('id', 'p_id', 'name','level');
            }])
            ->whereHas('children', function (){})
            ->get(['id', 'p_id', 'name', 'level'])
            ->toArray();

        $children = [];

        if ($category) {
            foreach ($category as $key => $value) {

                if (!strstr($value['name'], '阶段')) {
                    $children[] = $value['children'];
                } else {

                    $stageIds = array_pluck($value['children'], 'id');
                    $stage = Category::whereIn('id', $stageIds)
                        ->with('children')
                        ->get()
                        ->toArray();

                    $stageChildren = array_pluck($stage, 'children');
                    $children = array_merge($children, $stageChildren);
                }
            }

            $ids = [];
            foreach ($children as $key => $child) {
                foreach ($child as $k => $value) {
                    $ids[] = $value['id'];
                }
            }
        } else {
            $ids = Category::where('p_id', $q)->get()->pluck('id');
        }
        $files = Category::whereIn('id', $ids)
            ->get(['id', 'name as text']);

        return $files;
    }
}
